package com.da.demo.security.config;


import com.da.demo.filter.CaptChaFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-02-21
 * @Version: 1.0
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {

    private final CaptChaFilter captChaFilter;


    /**
     * <bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"> </bean>
     *
     * @return
     */
    @Bean  //配置一个spring的bean， bean的id就是方法名，bean的class就是方法的返回类型
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置安全过滤器链，定义了Spring Security的认证和授权规则。
     *
     * @param http HttpSecurity对象，用于配置Web安全相关的设置。
     * @return 配置好的SecurityFilterChain对象。
     * @throws Exception 如果在配置过程中出现异常。
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        // 打印日志，查看配置是否生效
//        System.out.println("Security configuration is applied.");
//
        SimpleUrlAuthenticationSuccessHandler simpleUrlAuthenticationSuccessHandler = new SimpleUrlAuthenticationSuccessHandler();
        simpleUrlAuthenticationSuccessHandler.setDefaultTargetUrl("/user/toWelcome");
        return http
                .csrf(AbstractHttpConfigurer::disable) // 关闭CSRF保护
                 // 配置表单登录
                .formLogin((formLogin) -> {
                    // 设置处理登录请求的URL
                    formLogin.loginProcessingUrl("/user/login")
                            // 设置登录页面的URL
                            .loginPage("/user/toLogin")
                            // 定制登录成功后跳转的地址/页面
                            .successHandler(simpleUrlAuthenticationSuccessHandler);
                })
                // 配置请求授权规则
                .authorizeHttpRequests(authorizeHttpRequests -> {
                    // 允许指定的URL无需认证即可访问
                    authorizeHttpRequests
                            .requestMatchers("/user/addUser").permitAll()
                            .requestMatchers("/user/toLogin").permitAll()
                            .requestMatchers("captcha").permitAll()
                            // 其他所有请求都需要进行身份验证
                            .anyRequest().authenticated();
                })
                // 在UsernamePasswordAuthenticationFilter之前添加自定义的验证码过滤器
                .addFilterBefore(captChaFilter, UsernamePasswordAuthenticationFilter.class)
                // 构建并返回SecurityFilterChain对象
                .build();
    }

}
